Date.prototype.format=function(fmt){
	if(!this.getTime()) return "";
	let o={"M+": this.getMonth() + 1,"d+": this.getDate(),"H+": this.getHours(),"m+": this.getMinutes(),"s+": this.getSeconds(),"q+": Math.floor((this.getMonth() + 3) / 3),"S": this.getMilliseconds()};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (let k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};
Date.prototype.formatShow=function(fmt){
	if(!this.getTime()) return "";
	let dateString=this.format(fmt);
	let str="";
	let date=new Date();
	if(date.getFullYear()==parseInt(dateString.substring(0,4))){
		if(date.getMonth()+1==parseInt(dateString.substring(5,7))){
			if(date.getDate()==parseInt(dateString.substring(8,10))){
				str="今天";
			}else if(date.getDate()-parseInt(dateString.substring(8,10))==1){
				str="昨天";
			}else if(date.getDate()-parseInt(dateString.substring(8,10))==-1){
				str="明天";
			}else if(date.getDate()-parseInt(dateString.substring(8,10))==2){
				str="前天";
			}else if(date.getDate()-parseInt(dateString.substring(8,10))==-2){
				str="后天";
			}else{
				str=parseInt(dateString.substring(5,7))+"月"+parseInt(dateString.substring(8,10))+"日";
			}
		}else{
			str=parseInt(dateString.substring(5,7))+"月"+parseInt(dateString.substring(8,10))+"日";
		}
		str=str+dateString.substring(10);
	}else{
		str=parseInt(dateString.substring(0,4))+"年"+parseInt(dateString.substring(5,7))+"月"+parseInt(dateString.substring(8,10))+"日"+dateString.substring(10);
	}
	return str;
};
Array.prototype.indexOf = function(val) {
	for (let i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};
Array.prototype.remove = function(val) {
	let index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};
function deepMerge(target,obj) {
    for(var key in obj){
        if (target[key] && obj[key] && typeof obj[key] === 'object') {
            obj[key]=deepMerge(target[key],obj[key])  // 递归
        }
    }
    return Object.assign(target,obj);
}
function formatNumber(num, pattern) {
    if(null==num || undefined==num) return "";
    if(pattern.substring(0,pattern.length-1)+"%"==pattern){
        return formatNumber(num*100.0,pattern.substring(0,pattern.length-1))+"%";
    }
	let fmtarr = pattern ? pattern.split('.') : [''];
	let decimals = (fmtarr.length > 1 ? fmtarr[1].length : 0);
	num = Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
	let strarr = num ? num.toString().split('.') : ['0'];
	let retstr = '';
	let str=strarr[0],fmt=fmtarr[0],i=str.length-1,comma = false;
	for (let f = fmt.length - 1; f >= 0; f--) {
		switch (fmt.substr(f, 1)) {
			case '#':
				if (i >= 0) retstr = str.substr(i--, 1) + retstr;
				break;
			case '0':
				if (i >= 0) retstr = str.substr(i--, 1) + retstr;
				else	retstr = '0' + retstr;
				break;
			case ',':
				comma = true;
				retstr = ',' + retstr;
				break;
		}
	}
	if (i >= 0) {
		if (comma) {
			let l = str.length;
			for (; i >= 0; i--) {
				retstr = str.substr(i, 1) + retstr;
				if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
			}
		}else retstr = str.substr(0, i + 1) + retstr;
	}
	retstr = retstr + '.';
	str = strarr.length > 1 ? strarr[1] : '';
	fmt = fmtarr.length > 1 ? fmtarr[1] : '';
	i = 0;
	for (let f = 0; f < fmt.length; f++) {
		switch (fmt.substr(f, 1)) {
			case '#':
				if (i < str.length) retstr += str.substr(i++, 1);
				break;
			case '0':
				if (i < str.length) retstr += str.substr(i++, 1);
				else retstr += '0';
				break;
		}
	}
	return retstr.replace(/^,+/, '').replace(/^-,+/, '-').replace(/\.$/, '');
}
var config={
    index:null,
    user:null,
    business:null,
    store:null,
    app:{},
    loadNum:0,
    loading:function(flag){
        if(flag) this.loadNum++;
        else this.loadNum--;
        if(config.index) config.index.setLoading(this.loadNum>0);
    },
    pageV3s:{},pagePvs:{},
    dictLoad:{},dictMap:{},dictString:{},dictLab:{},
    fn:{
        getHash:function(){
            let t=location.hash;
            return t.indexOf("#")==0?t:("#"+t);
        },
        popStateHandler:function(e){
            let hash=config.fn.getHash();
            let pv=null,sv=null;
            if(hash=="#"){
                pv=config.pagePvs["app0"];
                sv=config.pagePvs["app00"];
            }else if(hash.indexOf("#app")==0){
                let i=hash.substring(1);
                pv=config.pagePvs[i];
                sv=config.pagePvs[i+'0'];
            }
            if(pv){
                pv.isOpenPage=false;
                if(pv.backHandler){
                    pv.backHandler(sv.isBackFlag||false,sv.isBackObj||null);
                }
            }
        },
        backTempHash:function(){
            let hash=config.fn.getHash();
            if(hash.indexOf("#app")==0){
                history.back();
            }
        },
		fillJSONData:function(data,name,value){
			let flag=true;
			let index=0;
			let arr=name.split("");
			for(let i=0;i<arr.length;i++){
				if(arr[i]=="[") flag=false;
				else if(arr[i]=="]") flag=true;
				if(flag&&arr[i]=="."){
					index=i;
					break;
				}
			}
			if(index>0){
				let f1=name.substring(0,index);
				let f2=name.substring(f1.length+1);
				if(f1.indexOf("[")>-1&&f1.indexOf("]")==f1.length-1){
					let nm=f1.substring(0,f1.indexOf("["));
					let ni=f1.substring(nm.length+1,f1.length-1);
					if(isNaN(ni)){
						if(!data[nm]) data[nm]={};
						config.fn.fillJSONData(data[nm],ni+"."+f2,value);
					}else{
						if(!data[nm]) data[nm]=[];
						let n=parseInt(ni);
						for(let i=1;i<=n+1;i++){
							if(data[nm].length<i)data[nm].push({});
						}
						config.fn.fillJSONData(data[nm][n],f2,value);
					}
				}else{
					if(!data[f1]) data[f1]={};
					config.fn.fillJSONData(data[f1],f2,value);
				}
			}else{
				let f1=name;
				if(f1.indexOf("[")>-1&&f1.indexOf("]")==f1.length-1){
					let nm=f1.substring(0,f1.indexOf("["));
					let ni=f1.substring(nm.length+1,f1.length-1);
					if(isNaN(ni)){
						if(!data[nm]) data[nm]={};
						data[nm][ni]=value;
					}else{
						if(!data[nm]) data[nm]=[];
						if(!ni){
							data[nm]=value.split(',');
						}else{
							let n=parseInt(ni);
							for(let i=0;i<=n+1;i++){
								if(data[nm].length<i)data[nm].push(null);
							}
							data[nm][n]=value;
						}
					}
				}else{
					data[name]=value;
				}
			}
		},
		getJSONData:function(data,name){
			let flag=true;
			let index=0;
			let arr=name.split("");
			for(let i=0;i<arr.length;i++){
				if(arr[i]=="[") flag=false;
				else if(arr[i]=="]") flag=true;
				if(flag&&arr[i]=="."){
					index=i;
					break;
				}
			}
			if(index>0){
				let f1=name.substring(0,index);
				let f2=name.substring(f1.length+1);
				if(!data[f1]) data[f1]={};
				return config.fn.getJSONData(data[f1],f2);
			}else{
				return data[name];
			}
		},
        urlEncode:function(param, key, encode) {
            if(param==null) return '';
            let paramStr = '';
            let t = typeof (param);
            if (t == 'string' || t == 'number' || t == 'boolean') {
                paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
            } else {
                for (let i in param) {
                    let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                    paramStr += config.fn.urlEncode(param[i], k, encode);
                }
            }
            return paramStr;
        },
        getUrlParams:function(url){
            if(url.indexOf("?")<0) return {};
            let paramStr=url.substring(url.indexOf("?")+1);
            let ps={};
            let arr = paramStr.split("&");
            for(let i = 0; i < arr.length; i ++) {
                let ns=arr[i];
                let n=ns.indexOf("=");
                this.fillJSONData(ps,ns.substring(0,n),ns.substring(n+1));
            }
            return ps;
        },
    }
};
window.addEventListener("popstate",config.fn.popStateHandler, false);
var mixin={
	data(){
		return {
		    pageKey:'',
		    isOpenPage:false,
			backHandler:null,
            isBackFlag:false,isBackObj:null,
			user:null,
			dictLab:{}
		};
	},
	methods:{
        //提醒消息
        remind:function(color,msg){
            if(color && msg){
                config.index.remind(color,msg);
            }else{
                return {
                    success:function(msg){
                        config.index.remind('blue',msg);
                    },
                    error:function(msg){
                        config.index.remind('red',msg);
                    },
                    warn:function(msg){
                        config.index.remind('orange',msg);
                    }
                };
            }
        },
        //确认对话框
        confirm:function(title,desc,callback){
            config.index.confirm(title,desc,callback);
        },
        //请求
        requestData:function(url,params,fn,noMask,header){
            let flag=noMask?false:true;
            header=header||{};
            if(flag) config.loading(true);
            axios.post(url,params,{headers:header})
            .then(function(response) {
                if(flag) config.loading(false);
                fn(response.data);
            }.bind(this))
            .catch(function(error) {
                if(flag) config.loading(false);
                this.remind('red','请求错误');
                console.error(error);
            }.bind(this));
        },
        //子页面退出方法 关闭当前打开的页面
        back:function(flag,obj){
            config.fn.backTempHash();
            this.parentVue.isOpenPage=false;
            if(this.parentVue.backHandler){
                this.parentVue.backHandler(this.isBackFlag||flag,this.isBackObj||obj);
            }
        },
        //子页面不退出，预先设置退出参数
        setBack:function(flag,obj){
            this.isBackFlag=flag;
            this.isBackObj=obj;
        },
        //加载页面  指定id对象加载页面
        openPage:function(url,params,fn){
            this.isOpenPage=true;
            if(null==params) params={};
            params=deepMerge(params,config.fn.getUrlParams(url));
            config.loading(true);
            this.requestData(url, params, function(data) {
                config.loading(false);
                let json=typeof(data)=='object'?data:(new Function("return "+data))();
                if(json.msg){
                    this.remind('error',json.msg);
                    this.backHandler(false);
                }else{
                    let id=this.loadTemp(json,params,fn);
                    if(id!='app0') window.history.pushState({},id,location.pathname+location.search+"#"+id);
                }
            }.bind(this));
        },
        //加载模板
        loadTemp:function(data,params,fn){
            var id=this.pageKey+"0";
            if(null==params) params={};
            if(config.pageV3s[id]) config.pageV3s[id].unmount();
            let json=typeof(data)=='object'?data:(new Function("return "+data))();
            if(json.param){
                params=deepMerge(params,json.param);
                delete json.param;
            }
            json.template='<div>'
                +'<transition name="closeShow">'
                +'<block v-show="!isOpenPage">'+json.template+'</block>'
                +'</transition>'
                +'<transition name="pageShow">'
                +'<div v-if="isOpenPage" id="'+id+'0" class="m-page"></div>'
                +'</transition>'
                +'</div>';
            let v3=Vue.createApp(json,{param:params,parentVue:this});
            v3.mixin(mixin).use(component);
            config.pageV3s[id]=v3;
            let vv=v3.mount("#"+id);
            config.pagePvs[id]=vv;
            vv.pageKey=id;
            this.backHandler=fn;
            return id;
        },
		formatDay:function(date){
			return this.formatDate(date,'yyyy-MM-dd').formatShow('yyyy-MM-dd')
		},
		formatDate:function(date,style){
			if(!date){
				return "";
			}else if(date instanceof Date){
				return date.format(style);
			}else{
				return new Date(date.replace(/-/g, "/")).format(style);
			}
		},
		//四舍五入 d数字，n几位小数
		roundNumber:function(d,n){
			if(n<=0) return Math.round(d);
			let m=1;
			for(let i=0;i<n;i++) m*=10;
			return Math.round(d * m)/m;
		},
		formatNum:function(num){
			if(!num) return "0";
			return formatNumber(num,"#,##0");
		},
		formatAmount:function(amount){
			if(!amount) return "0.00";
			return formatNumber(amount,"#,##0.00");
		},
		formatNumber:function(num, pattern){
		    return formatNumber(num, pattern);
		},
		resetDict:function(type,fn){
			config.dictMap[type]=null;
			config.dictLoad[type]=false;
			this.initDict(type,fn);
		},
		clearDict:function(){
			config.dictMap={};
			config.dictLoad={};
			config.dictLab={};
		},
		//初始化字典
		initDict:function(type,fn){
			let mo=config;
			if(mo.dictMap[type]){
				if(fn) fn(mo.dictMap[type]);
				return true;
			}
			if(!mo.dictLoad[type]){
				mo.dictLoad[type]=true;
				if(type.startsWith("action/")){
					this.requestData(type,
					{},json=>{
						if(json.code==0){
							mo.dictMap[type]=json.map;
						}
						if(fn) fn(mo.dictMap[type]);
					});
				}else if(type.startsWith("@")){
					let arr=type.substring(1).split(",");
					let map={};
					for(let i=0;i<arr.length;i++){
						let strs=arr[i].split(":");
						map[strs[0]]=strs[1]+'|Y|';
					}
					mo.dictMap[type]=map;
					if(fn) fn(mo.dictMap[type]);
				}else{
					this.requestData('action/base/page/dict',
					{type:type},json=>{
						if(json.code==0){
							mo.dictMap[type]=json.map;
							mo.dictString[type]=json.mapString;
						}
						if(fn) fn(mo.dictMap[type]);
					});
				}
			}
			return false;
		},
		//展示字典
		dict:function(type,value,emptyTxt){
		    if(!value) return emptyTxt||'';
			this.initDict(type,(dictMap)=>{
				if(dictMap&&value){
					let arr=typeof(value)=='string'?value.split(","):value;
					let str="";
					for(let i=0;i<arr.length;i++){
						if(i!=0) str+=",";
						if(dictMap&&arr[i]){
							if(dictMap[arr[i]]){
								str+=dictMap[arr[i]].split("|")[0];
							}else{
								str+=arr[i];
							}
						}
					}
					this.dictLab[type+'-'+value]=str;
				}
			})
			return this.dictLab[type+'-'+value];
		},
		toDictOption:function(dictMap){
			if(dictMap){
				let obj=[];
			    if(typeof(dictMap)=='string'){
			        let ls=dictMap.split(',');
			        for(let i=0;i<ls.length;i++){
			            let kv=ls[i].split(':');
                        let arr=kv[1].split("|");
                        if(arr[1]=='Y'){
                            obj.push({label:arr[0],value:kv[0]});
                        }
			        }
			    }else{
                    for(let k in dictMap){
                        let arr=dictMap[k].split("|");
                        if(arr[1]=='Y'){
                            obj.push({label:arr[0],value:k});
                        }
                    }
			    }
				return obj;
			}else{
			    return [];
			}
		},
	}
};